﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;
using _3DHouse.CustomControl;
using _3DHouse.Lib;
using Microsoft.Win32;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight;


namespace _3DHouse
{
    /// <summary>
    /// 新界面.xaml 的交互逻辑
    /// </summary>
    public partial class Drawing : Window
    {
       
        public Drawing()
        {
            InitializeComponent();           
            //撤消，设置父容器
            unDoRedo.Container = World;
            //旋转方块摄像机
            ProjectionCamera myCamera = fangXiang.Camera as ProjectionCamera;
            oldFangXiangCamera = myCamera.Position;
            oldLookDirection = myCamera.LookDirection;
            oldUpDirection = myCamera.UpDirection;
            //三维场景添加变换
            Transform3DGroup _transform = new Transform3DGroup();
            RotateTransform3D rotate = new RotateTransform3D(_rotation);
            _transform.Children.Add(rotate);
            translate = new TranslateTransform3D();
            _transform.Children.Add(translate);
            World.Camera.Transform = _transform;
            fangXiang.Camera.Transform = rotate;
            //保存原来场景相机位置
            ProjectionCamera worldCamera = World.Camera as ProjectionCamera;
            oldWorldCameraPoint = worldCamera.Position;
            //创建方向指针 
            if (direction == null)
            {
                direction = new Direction();
                //direction.Transform = new TranslateTransform3D();                
            }
            GetTools();
            //地板           
            line = DrawFloor.WriteLine(200);
            World.Children.Add(line);
             floor = DrawFloor.WriteFloor(200);
            World.Children.Add(floor);
            //上传文件
             streamHelper = new FileManager.Client.FileStreamService.StreamHelper("1", "1");
             //上传文件的方法方法，返回上传是否成功
                 streamHelper.UploadFileCompleted += (k, j) =>
                 {
                     if (j.IsSuccess)
                     {
                         if (imgInfo.Count > 0)
                         {
                             Upload(imgInfo[0].ToString(), imgInfo[1].ToString());
                             imgInfo.Clear();                            
                             MessageBox.Show("保存成功");
                         } //删除文件
                         else if (imgInfo.Count == 0)
                         {
                             ClearFile();
                         }
                     }
                     else
                     {
                         MessageBox.Show("保存失败"+j.ErrorMessage);
                     }
                     //删除文件
                    // ClearFile();
                 };            
        }
        public Drawing(string _houseNum,string filePath)
        {
            InitializeComponent();
          
            //撤消，设置父容器
          //  unDoRedo.Container = World;
            //旋转方块摄像机
            ProjectionCamera myCamera = fangXiang.Camera as ProjectionCamera;
            oldFangXiangCamera = myCamera.Position;
            oldLookDirection = myCamera.LookDirection;
            oldUpDirection = myCamera.UpDirection;
            //三维场景添加变换
            Transform3DGroup _transform = new Transform3DGroup();
            RotateTransform3D rotate = new RotateTransform3D(_rotation);
            _transform.Children.Add(rotate);
            translate = new TranslateTransform3D();
            _transform.Children.Add(translate);
            World.Camera.Transform = _transform;
            fangXiang.Camera.Transform = rotate;
            //保存原来场景相机位置
            ProjectionCamera worldCamera = World.Camera as ProjectionCamera;
            oldWorldCameraPoint = worldCamera.Position;
            //创建方向指针 
            if (direction == null)
            {
                direction = new Direction();
                ////direction.Transform = new TranslateTransform3D();               
            }
            GetTools();
            try
            {
                OpenFile(filePath);
                m_filePath = filePath;
                houseNum = _houseNum;
                m_houseName = _houseNum + ".xml";
                lblTitle.Content = houseNum;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开文件失败,"+ ex.Message);
                this.Close();
            }
                //地板           
                line = DrawFloor.WriteLine(200);
                World.Children.Add(line);
                floor = DrawFloor.WriteFloor(200);
                World.Children.Add(floor);
                //上传文件
                streamHelper = new FileManager.Client.FileStreamService.StreamHelper("1", "1");
                //上传文件的方法方法，返回上传是否成功
                streamHelper.UploadFileCompleted += (k, j) =>
                {
                    if (j.IsSuccess)
                    {
                        if (imgInfo.Count > 0)
                        {
                            Upload(imgInfo[0].ToString(), imgInfo[1].ToString());
                            imgInfo.Clear();
                            MessageBox.Show("保存成功");
                        }
                        //删除文件
                        else if (imgInfo.Count == 0)
                        {
                            ClearFile();
                        }
                    }
                    else
                    {
                        MessageBox.Show("保存失败" + ","+j.ErrorMessage);
                    }
                };  
        }
        public Drawing(MemoryStream fileStream,string _hmId)
        {
            InitializeComponent();
          //获得户型图编号
            houseNum = _hmId;
            //撤消，设置父容器
            //  unDoRedo.Container = World;
            //旋转方块摄像机
            ProjectionCamera myCamera = fangXiang.Camera as ProjectionCamera;
            oldFangXiangCamera = myCamera.Position;
            oldLookDirection = myCamera.LookDirection;
            oldUpDirection = myCamera.UpDirection;
            //三维场景添加变换
            Transform3DGroup _transform = new Transform3DGroup();
            RotateTransform3D rotate = new RotateTransform3D(_rotation);
            _transform.Children.Add(rotate);
            translate = new TranslateTransform3D();
            _transform.Children.Add(translate);
            World.Camera.Transform = _transform;
            fangXiang.Camera.Transform = rotate;
            //保存原来场景相机位置
            ProjectionCamera worldCamera = World.Camera as ProjectionCamera;
            oldWorldCameraPoint = worldCamera.Position;
            //创建方向指针 
            if (direction == null)
            {
                direction = new Direction();
                direction.Transform = new TranslateTransform3D();
            }
            GetTools();
            try
            {
                OpenFile(fileStream);
                lblTitle.Content = houseNum;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开文件失败，"+ex.Message);         
            }
            //地板           
            line = DrawFloor.WriteLine(200);
            World.Children.Add(line);
            floor = DrawFloor.WriteFloor(200);
            World.Children.Add(floor);
            //上传文件
            streamHelper = new FileManager.Client.FileStreamService.StreamHelper("1", "1");
            //上传文件的方法方法，返回上传是否成功
            streamHelper.UploadFileCompleted += (k, j) =>
            {
                if (j.IsSuccess)
                {
                    if (imgInfo.Count > 0)
                    {
                        Upload(imgInfo[0].ToString(), imgInfo[1].ToString());
                        imgInfo.Clear();
                        MessageBox.Show("保存成功");                       
                    } 
                    //删除文件
                    else if (imgInfo.Count == 0)
                    {
                        ClearFile();
                    }
                }
                else
                {
                    MessageBox.Show("保存失败" + j.ErrorMessage);
                }
            };  
        }
      
        //上传文件
        string m_floder = "house\\";//本地保存文件夹
        string m_filePath ;//本地保存路径
        string m_houseName;//户型图名称
        FileManager.Client.FileStreamService.StreamHelper streamHelper;//上传对象
        ArrayList imgInfo;//记录图片信息用于上传
        public string houseNum;//户型图编号
        ModelVisual3D line ;//地板线
        ModelVisual3D floor ;
        TranslateTransform3D translate;
        //场景俯视视角 
        Vector3D lookDirection = new Vector3D(0.07, -1.88, -1.19);
        Vector3D upDirection = new Vector3D(-0.02, 0.86, -0.03);
        Point3D worldPoint3D = new Point3D(0, 39.47, 24.98);//场景相机位置
        Point3D fangXiangPoint3D = new Point3D(0, 5.33, 4.08);//方向方块相机位置
        //还原平视视角 
        Point3D oldWorldCameraPoint;//场景相机位置
        Point3D oldFangXiangCamera;//方向方块相机位置
        Vector3D oldLookDirection;
        Vector3D oldUpDirection;

        bool isWrite = false;//是否可绘
       Cube checkedModel;  //选中模型  
        string modelType;//模型类型           
        string modelName;//模型名称
        /**鼠标参数*/
        private bool mDown;// 鼠标按下状态。
        private Point mLastPos;//最后点击2dz坐标
        Point3D hitPoint;//鼠标点击坐标
        Point3D firstPoint;//第一次点击坐标
        Point3D lastPoint;//后一次点击坐标
            /*撤消重做*/
        UnDoRedo unDoRedo = new UnDoRedo();//撤消重做对象
        double movex; //移动距离，用于撤消
        double movey;
        double movez;
        /*场景旋转*/
        double mouseDeltaFactor = 2;//水平旋转角度
        Point mouseLastPosition;//水平旋转方向
        private Point _previousPosition2D;//前一次点击的位置
        private Vector3D _previousPosition3D = new Vector3D(0, 0, 1);
        private bool winDown;//鼠标按下状态
        private AxisAngleRotation3D _rotation = new AxisAngleRotation3D();
        /**/
        Cube copyModel;//粘贴对象
        Cube oldModel = new Cube();//拉伸撤消保存坐标

        /*变换状态，移动、旋转、拉伸*/
        bool isTranslate = false;//是否是移动
        //bool isRotate = false;//是否是旋转
        bool isScale = false;//是否是拉伸
        bool isMoveWindow=false;
        bool zhiX = false;//移动的方向
        bool zhiY = false;
        bool zhiZ = false;
        Direction direction;//方向指针
        //记录上次点击的按钮
        private Button lastButton;

        ListBoxItem item;//工具箱选项
        string modelFilePath = "";//工具栏模型路径
        bool isSave = true;//是否保存
        
        #region  //获取物体命中测试
        public void HitTest(Point mouseposition)
        {
            PointHitTestParameters pointparams = new PointHitTestParameters(mouseposition);
            VisualTreeHelper.HitTest(World, null, HTResult, pointparams);
        }
        //命中测试的回调函数
        //以下代码中的 HitTestResultBehavior 确定如何处理命中测试结果。
        public HitTestResultBehavior HTResult(System.Windows.Media.HitTestResult rawResult)
        {
            RayHitTestResult rayResult = rawResult as RayHitTestResult;
            if (rayResult != null)
            {
                //命中的网格.
                RayMeshGeometry3DHitTestResult rayMeshResult = rayResult as RayMeshGeometry3DHitTestResult;
                if (rayMeshResult != null)
                {//判断是否是复合网格
                    ModelVisual3D hitModel = rayMeshResult.VisualHit as ModelVisual3D;
                    //单个网格
                    GeometryModel3D hitGeo = rayMeshResult.ModelHit as GeometryModel3D;
                    MeshGeometry3D hitMesh = hitGeo.Geometry as MeshGeometry3D;
                    Point3D p1 = hitMesh.Positions.ElementAt(rayMeshResult.VertexIndex1);//返回序列中指定索引处的元素
                    double weight1 = rayMeshResult.VertexWeight1;// 网格三角形的第一个顶点与该三角形和命中测试的相交点的相对基值，用0到1之间的值表示。
                    Point3D p2 = hitMesh.Positions.ElementAt(rayMeshResult.VertexIndex2);
                    double weight2 = rayMeshResult.VertexWeight2;
                    Point3D p3 = hitMesh.Positions.ElementAt(rayMeshResult.VertexIndex3);
                    double weight3 = rayMeshResult.VertexWeight3;
                    //点击的三维坐标点
                    Point3D prePoint = new Point3D(p1.X * weight1 + p2.X * weight2 + p3.X * weight3, p1.Y * weight1 + p2.Y * weight2 + p3.Y * weight3, p1.Z * weight1 + p2.Z * weight2 + p3.Z * weight3);
                    hitPoint = prePoint;//记录点击坐标                           
                    if (isWrite)//可写
                    {
                        CreateModel();
                    }
                    else//选中
                    {
                        try
                        {
                            zhiX = false;
                            zhiY = false;
                            zhiZ = false;
                            if (hitModel is Direction) { }
                            else if (hitModel is DirectionX)
                            {
                                zhiX = true;
                            }
                            else if (hitModel is DirectionY)
                            {
                                zhiY = true;
                            }
                            else if (hitModel is DirectionZ)
                            {
                                zhiZ = true;
                            }
                            else if (hitModel is Cube)//选中物体
                            {  //在选中前清楚方向指针

                                Cube cube = hitModel as Cube;
                               
                                CheckType(cube);
                            }
                            else
                            {
                                //点的是地板   
                                if (checkedModel != null)
                                {
                                    checkedModel.Children.Remove(direction);
                                    Cursor = Cursors.Arrow;
                                }
                                checkedModel = null;                               
                               // txtModelType.Text = "";
                               // txtModelText.Text = "";
                                //lblText.Visibility = Visibility.Hidden;
                               // txtModelText.Visibility = Visibility.Hidden;
                                //txtModelName.Text = "";
                                //lblName.Visibility = Visibility.Hidden;
                                //txtModelName.Visibility = Visibility.Hidden;
                                //tabTransform.Visibility = Visibility.Hidden;
                                attributeContent.Visibility = Visibility.Hidden;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return HitTestResultBehavior.Stop;
                        }
                    }
                }
            }
            //对可视化树层次结构中的下一个可视对象继续进行命中测试
            return HitTestResultBehavior.Stop;
        }
        /// <summary>
        /// 创建模型
        /// </summary>
        private void CreateModel()
        {
            
            Cube model = null;//创建模型           
            
            try
            {
                ModelVisual3D cube = null;
                //打开模型文件
                using (FileStream file = new FileStream(modelFilePath, FileMode.Open))
                {
                    cube = XamlReader.Load(file) as ModelVisual3D;
                }
                if (cube == null)
                {
                    return;
                }
                if (cube.GetType().Name == "Sensor")
                {
                    model = cube as Sensor;
                }
                else
                {
                    model = cube as Cube;
                }
                //model.Type = modelType;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isWrite = false;
                return;
            }
            //设置平移位置，这里是原点（0,0,0）到点击点的向量，省略了计算
            Vector3D vect = new Vector3D(hitPoint.X + 0.001, hitPoint.Y + 0.001, hitPoint.Z + 0.001);
            TranslateTransform3D transLate = new TranslateTransform3D(vect);
              model.Transform = transLate; //模型移动到这个点  
              //创建时选中      
              CheckType(model);
            //碰撞检测
            TestCollision(hitPoint.X, hitPoint.Z);
            World.Children.Add(model);//场景中添加模型
            //调用接口中方法
            unDoRedo.InsertInUnDoRedoForInsert(model);
            isWrite = false;//设置不可写，不连续写            
            isSave = false;//没有保存
        }
        /// <summary>
        /// 判断选中类型      
        /// </summary>
        /// <param name="hitModel">选中的模型</param>
        public void CheckType(Cube hitModel)
        {
            //选中模型           
            //btnZuoRote.IsEnabled = true;
            //btnYouRote.IsEnabled = true; 
            if (checkedModel == null)
            {
                checkedModel = hitModel;
            }
            else if (checkedModel != hitModel)//不是同一个物体
            {
                if (checkedModel.Children.Contains(direction))
                {
                    checkedModel.Children.Remove(direction);
                }
                checkedModel = hitModel;
            }
            //判断Text属性是否有值
            if (hitModel.Text != null)
            {
                txtModelText.Text = hitModel.Text;
            }
            else
            {
                txtModelText.Text = "";
            }
            //类型名称
            txtModelType.Text = hitModel.Type;
            if (hitModel.GetType().Name.Equals("Cube"))//如果是Cube类屏蔽一些属性
            {
               // lblAlarmColor.Visibility = Visibility.Hidden;
               // txtAlarmColor.Visibility = Visibility.Hidden;
                lblText.Visibility = Visibility.Hidden;
                txtModelText.Visibility = Visibility.Hidden;
                lblName.Visibility = Visibility.Hidden;
                txtModelName.Visibility = Visibility.Hidden;
            }
            else if (hitModel.GetType().Name.Equals("Sensor"))
            {
               // lblAlarmColor.Visibility = Visibility.Visible;
               // txtAlarmColor.Visibility = Visibility.Visible;
                lblText.Visibility = Visibility.Visible;
                txtModelText.Visibility = Visibility.Visible;
                lblName.Visibility = Visibility.Visible;
                txtModelName.Visibility = Visibility.Visible;
                //模型名称
                txtModelName.Text = hitModel.Name;
            }
          //判断是否可更改尺寸
            if (!hitModel.Resize)
            {
                btnSize.IsEnabled = false;
            }
            else
            {
                btnSize.IsEnabled = true;
            }
            GetModelSize();
            attributeContent.Visibility = Visibility.Visible;
        }       

        #endregion
        #region  鼠标事件
        //viewport3d点击事件
        private void Word_MouseDown(object sender, MouseButtonEventArgs e)
        {
            grid.Focus();
            if (e.LeftButton == MouseButtonState.Pressed)//处于按下状态
            {
                mLastPos = Mouse.GetPosition(World);//鼠标点击的二维坐标点
                // Point mousepoint = e.GetPosition(World);
                HitTest(mLastPos);//命中测试获取点击的三维点和模型
                mDown = true;//鼠标按下状态
                //前一次点击的三维坐标      
                firstPoint = hitPoint;
               
                //拉伸变换状态
                if (isScale)
                {
                    //添加指针
                    
                    if (checkedModel != null)
                    {
                        if (checkedModel.Resize)
                    {
                        GetDirection();
                    }
                        SetOldModel();
                        //判断指针方向，设置不同鼠标指针图案
                        if (zhiX)
                        {
                            Cursor = Cursors.SizeWE;
                        }
                        else if (zhiY)
                        {
                            Cursor = Cursors.Arrow;
                        }
                        else if (zhiZ)
                        {
                            Cursor = Cursors.SizeNS;
                        }
                        else
                        {
                            Cursor = Cursors.Arrow;
                        }
                    }
                }
                if (isTranslate)
                {
                    if (checkedModel != null)
                    {
                        if (zhiX)
                        {
                            Cursor = Cursors.ScrollWE;
                        }
                        else if (zhiY)
                        {
                            Cursor = Cursors.ScrollNS;
                        }
                        else if (zhiZ)
                        {
                            Cursor = Cursors.ScrollNS;
                        }
                        else
                        {
                            Cursor = Cursors.ScrollAll;
                        }
                        GetDirection();
                    }
                }
               
            }
        }


        //viewport3d鼠标滑过事件
        private void Word_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                return;//不是按下状态
            }
            if (mDown == false)// || checkedModel == null)
            {//判断是否在Word_MouseDown事件中按下
                return;
            }
            //鼠标点击的二维坐标点
            Point pos = Mouse.GetPosition(World);
            double num2Dx = (pos.X - mLastPos.X) / 65;//平移值65可以算出来
            double num2Dy = (pos.Y - mLastPos.Y) / 65;
            //移动中的3D命中测试，只获得hitPoint的值,并且是后一次点击lastPoint
            MoveHitTest(pos);            
            lastPoint = hitPoint;//后一次点击3D坐标
         
            //3D坐标分量的改变值
            double numx = lastPoint.X - firstPoint.X;
            double numz = lastPoint.Z - firstPoint.Z;
            double numy = lastPoint.Y - firstPoint.Y;
            //Console.WriteLine(lastPoint + "  " + firstPoint);
            //Console.WriteLine(numx + "  " + numz);
           // movex += num2Dx;
            //累加改变值
            if (zhiX) { movex += num2Dx; }
            if (zhiY) { movey -= num2Dy; }
            if (zhiZ) { movez += num2Dy; }
            double weiyi = Math.Sqrt(num2Dx * num2Dx + num2Dy * num2Dy);
            //改变大小
            if (isScale)
            {
                if (zhiX)
                {
                    if (num2Dx < 0&&checkedModel.Content.Bounds.SizeX<0.1)
                    {
                        return;
                    }

                    FlexByRound(num2Dx / checkedModel.Content.Bounds.SizeX);
                    
                   // Console.WriteLine(num2Dx + " " + checkedModel.Content.Bounds.SizeX);
                    //FlexByRound(num2Dx);
                    //Console.WriteLine(num2Dx + " " + checkedModel.Content.Bounds.SizeX);
                    TestCollision(num2Dx / checkedModel.Content.Bounds.SizeX, 0);
                   
                }
                else if (zhiY)
                {
                    if (num2Dy > 0 && checkedModel.Content.Bounds.SizeY < 0.1)
                    {
                        return;
                    }
                    FlexByUptoDown(-num2Dy / checkedModel.Content.Bounds.SizeY);
                   TestCollision(0, -num2Dy / checkedModel.Content.Bounds.SizeY);
                }
                else if (zhiZ)
                {
                    if (num2Dy < 0 && checkedModel.Content.Bounds.SizeZ < 0.1)
                    {
                        return;
                    }
                    FlexByFrontToBack(num2Dy / checkedModel.Content.Bounds.SizeZ);
                    TestCollision(0, num2Dy / checkedModel.Content.Bounds.SizeZ);
                }
            }
            //挪动
            else if (isTranslate)
            {

                if (zhiX)
                {
                    SetTranslateRound(num2Dx);
                    TestCollision(num2Dx, 0);
                }
                else if (zhiY)
                {
                    SetTranslateUpToDown(-num2Dy);
                    //上下移动还没写碰撞检测
                }
                else if (zhiZ)
                {
                    SetTranslateFrontToBack(num2Dy);
                    /*碰撞检测*/
                    TestCollision(0, num2Dy);
                }
                else
                {
                    movez += numz;
                    movex += numx;                  
                    SetTranslateRound(numx); 
                    TestCollision(numx, 0);
                    SetTranslateFrontToBack(numz);
                    /*碰撞检测*/
                    TestCollision(0, numz);
                }
            }
            else if (isMoveWindow)//拖动地板移动视角
            {
                //double x = 0;
                //double z = 0;
                //if (_rotation.Angle > 0)
                //{
                //   // x = num2Dx / Math.Sin(_rotation.Angle);
                //   // z = num2Dx / Math.Tan(_rotation.Angle);
                //    x = num2Dx * Math.Sin(_rotation.Angle);
                //    z = num2Dx / Math.Tan(_rotation.Angle);
                //}
               // Console.WriteLine("2dX:"+num2Dx+" 2DY:"+num2Dy+"__3DX:"+numx+" 3DZ:"+numz);
                //摄像机位移时导致三维空间在二维呈现的区域变换，当鼠标移动到某个三维点时摄像机随后也移动了，这导致鼠标这时候对应的点往回退了，这样下次移动计算时方向就反了就好看的颤抖。
                MoveCam(numx*0.8, numz*0.8);
                //SetCursorPos((int)pos.X, (int)pos.Y);
            }
            mLastPos = pos;
            firstPoint = lastPoint;
        }
        //viewport3d鼠标弹起事件
        private void Word_MouseUp(object sender, MouseButtonEventArgs e)
        {
            mDown = false;//设置鼠标弹起状态
            modelName = "";//清空模型名称 
            if (Cursor == Cursors.Pen)
            {
                Cursor = Cursors.Arrow;
            }
            if (checkedModel != null)
            {
                if (isScale && (movez != 0 || movex != 0||movex != 0))//设置撤消改变的大小
                {
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
                if (isTranslate && (movey != 0 || movez != 0 || movex != 0))
                {
                    unDoRedo.InsertInUnDoRedoForMove(movex, movey, movez, checkedModel);
                    isSave = false;//没有保存
                }
            }
            //if (isMoveWindow)//拖动地板移动视角
            //{
            //    MoveCam(movex, movez);
            //    //Console.WriteLine("挪地图："+numx);
            //}
            //归零重新计数
            movey = 0;
            movex = 0;
            movez = 0;
        }
        #region  鼠标光标改变
       
        private void World_MouseLeave(object sender, MouseEventArgs e)
        {
            Cursor = Cursors.Arrow;
        }
        #endregion
        #endregion
        #region  //移动物体时命中测试
        public void MoveHitTest(Point mouseposition)
        {
            PointHitTestParameters pointparams = new PointHitTestParameters(mouseposition);
            VisualTreeHelper.HitTest(World, null, MoveResult, pointparams);
        }
        //命中测试的回调函数
        //以下代码中的 HitTestResultBehavior 确定如何处理命中测试结果。
        public HitTestResultBehavior MoveResult(System.Windows.Media.HitTestResult rawresult)
        {
            RayHitTestResult rayResult = rawresult as RayHitTestResult;
            if (rayResult != null)
            {
                //命中的网格.
                RayMeshGeometry3DHitTestResult rayMeshResult = rayResult as RayMeshGeometry3DHitTestResult;
                if (rayMeshResult != null)
                {//判断是否是复合网格
                    ModelVisual3D hitModel = rayMeshResult.VisualHit as ModelVisual3D;
                    //单个网格
                    GeometryModel3D hitgeo = rayMeshResult.ModelHit as GeometryModel3D;
                    MeshGeometry3D hitmesh = hitgeo.Geometry as MeshGeometry3D;
                    Point3D p1 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex1);//返回序列中指定索引处的元素
                    double weight1 = rayMeshResult.VertexWeight1;// 网格三角形的第一个顶点与该三角形和命中测试的相交点的相对基值，用 0 到 1 之间的值表示。
                    Point3D p2 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex2);
                    double weight2 = rayMeshResult.VertexWeight2;
                    Point3D p3 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex3);
                    double weight3 = rayMeshResult.VertexWeight3;

                    //点击的三维坐标点
                    Point3D prePoint = new Point3D(p1.X * weight1 + p2.X * weight2 + p3.X * weight3, p1.Y * weight1 + p2.Y * weight2 + p3.Y * weight3, p1.Z * weight1 + p2.Z * weight2 + p3.Z * weight3);
                    hitPoint = prePoint;//记录点击坐标
                   
                }
            }
            return HitTestResultBehavior.Stop;
        }
        #endregion
        #region   伸缩操作
        /// <summary>
        /// 拖拽左右伸缩
        /// </summary>
        /// <param name="n">拉伸数值</param>
        private void FlexByRound(double n)
        {           
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    TranslateTransform3D Translate = null;//平移
                    ScaleTransform3D Flex = null;//伸缩
                    RotateTransform3D rotate = null;//旋转
                    #region 遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            Flex = tr as ScaleTransform3D;
                            Flex.ScaleX += n;
                            //设置方向指针移到                         
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            Translate = tr as TranslateTransform3D;
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rotate = tr as RotateTransform3D;
                        }
                    }
                    if (Flex == null)
                    {
                        Flex = new ScaleTransform3D();
                        Flex.ScaleX += n;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(Flex);
                        if (Translate != null)
                        {
                            tfg2.Children.Add(Translate);
                        }
                        if (rotate != null)
                        {
                            tfg2.Children.Add(rotate);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D transLate = checkedModel.Transform as TranslateTransform3D;
                    ScaleTransform3D flex = new ScaleTransform3D();
                    flex.ScaleX += n;
                    tfg.Children.Add(flex);
                    tfg.Children.Add(transLate);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
                GetModelSize();
            }

        }
        /// <summary>
        /// 拖拽前后伸缩
        /// </summary>
        /// <param name="n">拉伸数值</param>
        private void FlexByFrontToBack(double n)
        {
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    TranslateTransform3D tran = null;
                    ScaleTransform3D sca = null;
                    RotateTransform3D rota = null;
                    #region 遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            sca = tr as ScaleTransform3D;
                            sca.ScaleZ += n;
                            //设置方向指针移到
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tran = tr as TranslateTransform3D;
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rota = tr as RotateTransform3D;
                        }
                    }
                    if (sca == null)
                    {
                        sca = new ScaleTransform3D();
                        sca.ScaleZ += n;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(sca);
                        if (tran != null)
                        {
                            tfg2.Children.Add(tran);
                        }
                        if (rota != null)
                        {
                            tfg2.Children.Add(rota);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    ScaleTransform3D sca = new ScaleTransform3D();
                    sca.ScaleZ += n;
                    tfg.Children.Add(sca);
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
                GetModelSize();
            }
        }
      /// <summary>
      /// 上下拉伸
      /// </summary>
      /// <param name="n">拉伸数值</param>
        private void FlexByUptoDown(double n)
        {
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    TranslateTransform3D tran = null;
                    ScaleTransform3D sca = null;
                    RotateTransform3D rota = null;
                    #region 遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            sca = tr as ScaleTransform3D;
                            sca.ScaleY += n;
                            //设置方向指针移到
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tran = tr as TranslateTransform3D;
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rota = tr as RotateTransform3D;
                        }
                    }
                    if (sca == null)
                    {
                        sca = new ScaleTransform3D();
                        sca.ScaleZ += n;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(sca);
                        if (tran != null)
                        {
                            tfg2.Children.Add(tran);
                        }
                        if (rota != null)
                        {
                            tfg2.Children.Add(rota);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    ScaleTransform3D sca = new ScaleTransform3D();
                    sca.ScaleY += n;
                    tfg.Children.Add(sca);
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
                GetModelSize();
            }
        }
        #endregion
        #region  平移操作
        /// <summary>
        /// 设置前后平移
        /// </summary>
        /// <param name="n">平移值double类型</param>
        private void SetTranslateFrontToBack(double n)
        {
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    RotateTransform3D rotate = null;//旋转
                    ScaleTransform3D flex = null;//伸缩
                    TranslateTransform3D tranLate = null;//平移
                    #region  遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            flex = tr as ScaleTransform3D;

                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tranLate = tr as TranslateTransform3D;
                            tranLate.OffsetZ = n;
                            //设置方向指针移到
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rotate = tr as RotateTransform3D;
                        }
                    }
                    if (tranLate == null)
                    {
                        tranLate = new TranslateTransform3D();
                        tranLate.OffsetZ = n;
                        Transform3DGroup tfgNew = new Transform3DGroup();
                        tfgNew.Children.Add(tranLate);
                        if (tranLate != null)
                        {
                            tfgNew.Children.Add(tranLate);
                        }
                        if (rotate != null)
                        {
                            tfgNew.Children.Add(rotate);
                        }
                        checkedModel.Transform = tfgNew;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    tran.OffsetZ = n;
                    tfg.Children.Add(tran);
                    //设置方向指针移到
                    GetDirection();
                    checkedModel.Transform = tfg;
                }
                else if (checkedModel.Transform == null)
                {
                    TranslateTransform3D tran = new TranslateTransform3D(0, 0, n);
                    tfg.Children.Add(tran);
                    //设置方向指针移到                    
                    GetDirection();
                    checkedModel.Transform = tfg;
                }
            }
        }
        /// <summary>
        /// 设置左右平移
        /// </summary>
        /// <param name="n">平移值double类型</param>
        private void SetTranslateRound(double n)
        {
           
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    RotateTransform3D rota = null;
                    ScaleTransform3D sca = null;
                    TranslateTransform3D tran = null;
                    #region 遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            sca = tr as ScaleTransform3D;

                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tran = tr as TranslateTransform3D;
                            tran.OffsetX += n;
                            //设置方向指针移到
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rota = tr as RotateTransform3D;
                        }
                    }
                    if (tran == null)
                    {
                        tran = new TranslateTransform3D();
                        tran.OffsetX += n;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(tran);
                        if (sca != null)
                        {
                            tfg2.Children.Add(sca);
                        }
                        if (rota != null)
                        {
                            tfg2.Children.Add(rota);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    tran.OffsetX += n;
                    tfg.Children.Add(tran);
                    //设置方向指针移到
                    GetDirection();
                    checkedModel.Transform = tfg;
                }
                else if (checkedModel.Transform == null)
                {
                    TranslateTransform3D tran = new TranslateTransform3D(n, 0, 0);
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
            }
        }
        /// <summary>
        /// 设置上下平移
        /// </summary>
        /// <param name="n">平移值double类型</param>
        private void SetTranslateUpToDown(double n)
        {
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    RotateTransform3D rota = null;
                    ScaleTransform3D sca = null;
                    TranslateTransform3D tran = null;
                    #region  遍历Transform3DGroup的子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            sca = tr as ScaleTransform3D;

                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tran = tr as TranslateTransform3D;
                            tran.OffsetY = n;
                            //设置方向指针移到
                            GetDirection();
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rota = tr as RotateTransform3D;
                        }
                    }
                    if (tran == null)
                    {
                        tran = new TranslateTransform3D();
                        tran.OffsetY = n;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(tran);
                        if (sca != null)
                        {
                            tfg2.Children.Add(sca);
                        }
                        if (rota != null)
                        {
                            tfg2.Children.Add(rota);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    tran.OffsetY = n;
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
                else if (checkedModel.Transform == null)
                {
                    TranslateTransform3D tran = new TranslateTransform3D(0, 0, 0);
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                    //设置方向指针移到
                    GetDirection();
                }
            }
        }
        #endregion
        #region  旋转操作
        /// <summary>
        /// 设置左右旋转
        /// </summary>
        /// <param name="n">平移值double类型</param>
        private void SetRotateRound(double n)
        {
            if (checkedModel != null)
            {
                Transform3DGroup tfg = new Transform3DGroup();
                //组合变换
                if (checkedModel != null && checkedModel.Transform != null && checkedModel.Transform.GetType().Name.Equals("Transform3DGroup"))
                {
                    tfg = checkedModel.Transform as Transform3DGroup;
                    RotateTransform3D rota = null;
                    ScaleTransform3D sca = null;
                    TranslateTransform3D tran = null;
                    #region  遍历Transform3DGroup子集，根据类型进行操作
                    foreach (Transform3D tr in tfg.Children)
                    {
                        if (tr.GetType().Name.Equals("ScaleTransform3D"))
                        {
                            sca = tr as ScaleTransform3D;

                        }
                        else if (tr.GetType().Name.Equals("TranslateTransform3D"))
                        {
                            tran = tr as TranslateTransform3D;
                        }
                        else if (tr.GetType().Name.Equals("RotateTransform3D"))
                        {
                            rota = tr as RotateTransform3D;
                            AxisAngleRotation3D axi = rota.Rotation as AxisAngleRotation3D;
                            axi.Angle += n;

                        }
                    }
                    if (rota == null)
                    {
                        rota = new RotateTransform3D();
                        AxisAngleRotation3D axi = new AxisAngleRotation3D();
                        axi.Angle = n;
                        axi.Axis = new Vector3D(0, 1, 0);
                        rota.Rotation = axi;
                        Transform3DGroup tfg2 = new Transform3DGroup();
                        tfg2.Children.Add(rota);
                        if (sca != null)
                        {
                            tfg2.Children.Add(sca);
                        }
                        if (tran != null)
                        {
                            tfg2.Children.Add(tran);
                        }
                        checkedModel.Transform = tfg2;
                    }
                    #endregion
                }
                else if (checkedModel != null && checkedModel.Transform != null)
                {//单个位移                 
                    TranslateTransform3D tran = checkedModel.Transform as TranslateTransform3D;
                    RotateTransform3D rota = new RotateTransform3D();
                    AxisAngleRotation3D axi = new AxisAngleRotation3D();
                    axi.Angle = n;
                    axi.Axis = new Vector3D(0, 1, 0);
                    rota.Rotation = axi;
                    tfg.Children.Add(rota);
                    tfg.Children.Add(tran);
                    checkedModel.Transform = tfg;
                }
            }
        }
        #endregion
        #region 碰撞检测
        /// <summary>
        /// 碰撞检测
        /// </summary>       
        /// <param name="x">X轴方向移动的距离</param>
        /// <param name="z">Z轴方向移动的距离</param>
        public void TestCollision(double x, double z)
        {
            if (checkedModel == null) { return; }
            //获取选中的对象的边界框         
            GeometryModel3D geom = checkedModel.Content as GeometryModel3D;
            foreach (ModelVisual3D element in World.Children)
            {
                // ModelVisual3D model = element as ModelVisual3D;
                if (element == checkedModel)
                {
                    continue;
                }
                if (element is Cube == false)
                {
                    continue;
                } if (checkedModel.Content==null||element.Content == null)
                {
                    continue;
                }
                if (checkedModel.Content.Bounds.IntersectsWith(element.Content.Bounds))//Model3DGroup没有变化，所以得出来的是原始值.选中的物体的Bounds加上x宽度在加上位移。
                {
                    Separate(element, checkedModel, x, z);
                    mDown = false;
                    return;
                }
            }
        }
        /// <summary>
        /// 碰撞后分离   
        /// </summary>
        /// <param name="cube">被撞物体</param>
        /// <param name="cube2">当前物体</param>
        /// <param name="x">X轴方向移动的距离</param>
        /// <param name="z">Z轴方向移动的距离</param>    
        void Separate(ModelVisual3D beHitCube, ModelVisual3D HitCube, double x, double y)
        {
            //对比对象的前后边界值最大最小值
            Rect3D rect = beHitCube.Content.Bounds;
            double beHitMaxX = rect.X + rect.SizeX;
            double beHitMinX = rect.X;
            double beHitMaxZ = rect.Z + rect.SizeZ;
            double beHitMinZ = rect.Z;
            //移动对象边界值
            Rect3D rect2 = HitCube.Content.Bounds;
            double hitMaxX = rect2.X + rect2.SizeX;
            double hitMinX = rect2.X;
            double hitMaxZ = rect2.Z + rect2.SizeZ;
            double hitMinZ = rect2.Z;

            //回退方向 从左到右
            if (x > 0)
            {
                double cha = beHitMinX - hitMaxX - 0.01;//加0.001放置重合，重合时动一动就会触发碰撞方法
                //让移动的和对比的面重合
                SetTranslateRound(cha);
            }
            else if (x < 0)//右到左
            {
                double cha = beHitMaxX - hitMinX + 0.01;
                //让移动的和对比的面重合
                SetTranslateRound(cha);
            } if (y > 0)//后到前
            {
                double cha = beHitMinZ - hitMaxZ - 0.01;
                SetTranslateFrontToBack(cha);
            }
            else if (y < 0)//前到后
            {
                double cha = beHitMaxZ - hitMinZ + 0.01;
                SetTranslateFrontToBack(cha);
            }
        }
        #endregion
                       
        #region 控制场景
        //方块点击事件
        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;
            //Point pos = Mouse.GetPosition(World);
            // mouseLastPosition = pos;
            /**/
            _previousPosition2D = e.GetPosition(fangXiang);//不能用this
            _previousPosition3D = ProjectToTrackball(fangXiang.ActualWidth, fangXiang.ActualHeight,
                                                     _previousPosition2D);
        }
       //方块鼠标移动
        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
               
                /**/

                Point currentPosition = e.GetPosition(fangXiang);
                // avoid any zero axis conditions
                if (currentPosition == _previousPosition2D) return;
                Track(currentPosition, fangXiang.ActualWidth, fangXiang.ActualHeight);
                _previousPosition2D = currentPosition;
                /**/ 
                //Point newMousePosition = e.GetPosition(this);
                //if (mouseLastPosition.X != newMousePosition.X)
                //{
                //    HorizontalTransform(mouseLastPosition.X < newMousePosition.X, mouseDeltaFactor);
                //}

                //if (mouseLastPosition.Y != newMousePosition.Y)// change position in the horizontal direction
                //{

                //    VerticalTransform(mouseLastPosition.Y > newMousePosition.Y, mouseDeltaFactor);
                //}
                //mouseLastPosition = newMousePosition;
            }
        }
       //方块鼠标弹起
        private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //mDown = false;
        }
      //垂直旋转
        private void VerticalTransform(bool upDown, double angleDeltaFactor)
        {
            ProjectionCamera myCamera = World.Camera as ProjectionCamera;
            Vector3D postion = new Vector3D(camera.Position.X, camera.Position.Y, camera.Position.Z);
            Vector3D rotateAxis = Vector3D.CrossProduct(postion, camera.UpDirection);
            RotateTransform3D rt3d = new RotateTransform3D();
            AxisAngleRotation3D rotate = new AxisAngleRotation3D(rotateAxis, angleDeltaFactor * (upDown ? -1 : 1));
            rt3d.Rotation = rotate;
            Matrix3D matrix = rt3d.Value;
            Point3D newPostition = matrix.Transform(camera.Position);
            camera.Position = newPostition;
            camera.LookDirection = new Vector3D(-newPostition.X, -newPostition.Y, -newPostition.Z);

            //update the up direction
            Vector3D newUpDirection = Vector3D.CrossProduct(camera.LookDirection, rotateAxis);
            newUpDirection.Normalize();
            camera.UpDirection = newUpDirection;
            //大场景
            Point3D bigPostition = matrix.Transform(myCamera.Position);
            myCamera.Position = bigPostition;
            // myCamera.LookDirection = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);

            //update the up direction
            // Vector3D bigUpDirection = Vector3D.CrossProduct(myCamera.LookDirection, rotateAxis);
            newUpDirection.Normalize();
            myCamera.UpDirection = newUpDirection;
            /**/
            //计算向量
            Vector3D vOld = myCamera.LookDirection;
            Vector3D vNew = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);//新的向量
            //第一取原来的摸
            double oldM = Math.Sqrt(vOld.X * vOld.X + vOld.Y * vOld.Y + vOld.Z * vOld.Z);
            //第二新摸
            double newM = Math.Sqrt(vNew.X * vNew.X + vNew.Y * vNew.Y + vNew.Z * vNew.Z);
            double newVecX = vNew.X / newM * oldM;
            double newVecY = vNew.Y / newM * oldM;
            double newVecZ = vNew.Z / newM * oldM;
            myCamera.LookDirection = new Vector3D(newVecX, newVecY, newVecZ);// _center - position;//设置新的观察方向
            /**/
        }
        /// <summary>
        /// 水平旋转
        /// </summary>
        /// <param name="leftRight">方向</param>
        /// <param name="angleDeltaFactor">角度</param>
        private void HorizontalTransform(bool leftRight, double angleDeltaFactor)
        {
            ProjectionCamera myCamera = World.Camera as ProjectionCamera;//场景摄像机
            Vector3D rotateAxis = camera.UpDirection;//向上方向的向量
            RotateTransform3D rt3d = new RotateTransform3D();
            AxisAngleRotation3D rotate = new AxisAngleRotation3D(rotateAxis, angleDeltaFactor * (leftRight ? -1 : 1));
            rt3d.Rotation = rotate;
            //空间转换的矩阵，两个摄像机公用
            Matrix3D matrix = rt3d.Value;
            //变换后的坐标
            Point3D newPostition = matrix.Transform(camera.Position);
            //给方块摄像机设置坐标
            camera.Position = newPostition;
            camera.LookDirection = new Vector3D(-newPostition.X, -newPostition.Y, -newPostition.Z);
            //大场景
            //变换后的坐标
            Point3D bigPostition = matrix.Transform(myCamera.Position);
            myCamera.Position = bigPostition;
            //计算向量
            Vector3D vOld = myCamera.LookDirection;
            Vector3D vNew = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);//新的向量
            //第一取原来的摸
            double oldM = Math.Sqrt(vOld.X * vOld.X + vOld.Y * vOld.Y + vOld.Z * vOld.Z);
            //第二新摸
            double newM = Math.Sqrt(vNew.X * vNew.X + vNew.Y * vNew.Y + vNew.Z * vNew.Z);
            double newVecX = vNew.X / newM * oldM;
            double newVecY = vNew.Y / newM * oldM;
            double newVecZ = vNew.Z / newM * oldM;
            myCamera.LookDirection = new Vector3D(newVecX, newVecY, newVecZ);// _center - position;//设置新的观察方向
        }
        /*窗口旋转场景***/
      
       /// <summary>
       /// 计算鼠标前后位置的角度
       /// </summary>
       /// <param name="currentPosition">当前鼠标位置</param>
        private void Track(Point currentPosition,double width,double height)
        {
            Vector3D currentPosition3D = ProjectToTrackball(
                width, height, currentPosition);

            Vector3D axis = Vector3D.CrossProduct(_previousPosition3D, currentPosition3D);
            double angle = Vector3D.AngleBetween(_previousPosition3D, currentPosition3D);         
            if (axis.Length == 0) return;
            Quaternion delta = new Quaternion(axis, -angle);
            Quaternion q = new Quaternion(_rotation.Axis, _rotation.Angle);
            // Compose the delta with the previous orientation构成的三角洲与以前的方向
            q *= delta;

            // Write the new orientation back to the Rotation3D 摄像机Rotation3D新方向
            if (q.Angle <40&&q.Angle>-45)
            {
                _rotation.Axis = q.Axis;
                _rotation.Angle = q.Angle;
            }
            _previousPosition3D = currentPosition3D;            
        }
        private Vector3D ProjectToTrackball(double width, double height, Point point)
        {
            double x = point.X / (width / 2);    // Scale so bounds map to [0,0] - [2,2]
            double y = point.Y / (height / 2);

            x = x - 1;                           // Translate 0,0 to the center
            y = 1 - y;                           // Flip so +Y is up instead of down

            double z2 = 1 - x * x - y * y;       // z^2 = 1 - x^2 - y^2
            double z = z2 > 0 ? Math.Sqrt(z2) : 0;

            return new Vector3D(x, y, z);
        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.RightButton == MouseButtonState.Pressed)
            {
                winDown = true;
                _previousPosition2D = e.GetPosition(World);
                _previousPosition3D = ProjectToTrackball(World.ActualWidth,
                                                        World. ActualHeight,
                                                         _previousPosition2D);
            }
           
        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            winDown = false;
        }
        //窗口鼠标移动事件，鼠标右键旋转场景
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.RightButton == MouseButtonState.Pressed)
            {
                if (!winDown)
                    return;
                Point currentPosition = e.GetPosition(World);
                // avoid any zero axis conditions
                if (currentPosition == _previousPosition2D) return;
                Track(currentPosition, World.ActualWidth, World.ActualHeight);
                _previousPosition2D = currentPosition;
            }
        }
        //相机移动
        void MoveCam(double x, double y)
        {
            translate.OffsetX -= x;
            translate.OffsetZ -= y;
        }
        //场景缩放
        private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            int n = e.Delta;
            int num = 1;
            if (n < 0)
            {
                num = -1;
            }
            PerspectiveCamera myCamera = World.Camera as PerspectiveCamera;
            ////相机位置
            var cameraPostion = myCamera.Position;
            ////相机看的方向
            var lookDirection = myCamera.LookDirection;
            /// 获取相机在3D投影的点 
            var x = cameraPostion.X + lookDirection.X * num;
            var y = cameraPostion.Y + lookDirection.Y * num;
            var z = cameraPostion.Z + lookDirection.Z * num;
            myCamera.Position = new Point3D(x, y, z);
        }
        #endregion
        #region 键盘功能快捷键
        private void World_KeyDown(object sender, KeyEventArgs e)
        {
            //保存 Ctrl+S 
            if (e.Key == Key.S && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                //判断是否是打开的文件
                //if (openFilePath == "")
                //{
                //    SaveFileDialog savedialog = new SaveFileDialog();
                //    savedialog.Filter = "xaml|*.xml|所有文件|*.*";
                //    if (savedialog.ShowDialog().Value)
                //    {
                //        openFilePath = savedialog.FileName;//保存后就是这个文件路径
                //        Save(openFilePath);
                //    }
                //    else
                //    {
                //        return;
                //    }
                //}
                //else
                //{
                //    Save(openFilePath);
                //}
                if (!isSave)
                {
                    Save();
                }
            }
            //上下左右键移动
            switch (e.Key)
            {
                case Key.Left: SetTranslateRound(-0.1); TestCollision(-0.1, 0); e.Handled = true; break;
                case Key.Right: SetTranslateRound(0.1); TestCollision(0.1, 0); e.Handled = true; break;
                case Key.Up: SetTranslateFrontToBack(-0.1); TestCollision(0, -0.1); e.Handled = true; break;
                case Key.Down: SetTranslateFrontToBack(0.1); TestCollision(0, 0.1); e.Handled = true; break;
                //case Key.Delete:
            }
            
            //删除 Delete
            if (e.Key == Key.Delete)
            {
                DelModel();
            }
            //撤销 Ctrl+Z
            if (e.Key == Key.Z && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                if (checkedModel != null)
                {
                    checkedModel.Children.Remove(direction);
                }
                unDoRedo.Undo(1);
            }
            //重做  Ctrl+Y
            if (e.Key == Key.Y && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                if (checkedModel != null)
                {
                    checkedModel.Children.Remove(direction);
                }
                unDoRedo.Redo(1);
            }
            //复制 Ctrl+C
            if (e.Key == Key.C && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                //copyModel = new Cube();
                NewCopy();
            }
            //粘贴
            if (e.Key == Key.V && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                Paste();
            }

        }
        /// <summary>
        /// 删除模型
        /// </summary>
        private void DelModel()
        {
            if (checkedModel != null)
            {
                if (World.Children.Remove(checkedModel))
                {
                    unDoRedo.InsertInUnDoRedoForDelete(checkedModel);
                    isSave = false;//没有保存
                    //删除指针
                    if (checkedModel.Children.Contains(direction))
                    {
                        checkedModel.Children.Remove(direction);
                    }
                    checkedModel = null;
                    modelName = "";
                    txtModelType.Text = "";
                }
            }
        }
        /// <summary>
        /// 粘贴封装的方法
        /// </summary>
        private void Paste()
        {
            if (copyModel != null && copyModel.Content != null)
            {
                Cube cube = new Cube();
                cube.Content = copyModel.Content.Clone();//复制内容
                cube.Type = copyModel.Type;
                //计算鼠标点击和当前坐标的差值         
                double x = hitPoint.X - cube.Content.Bounds.X;
                // double y = hitPoint.Y - cube.Content.Bounds.Y;
                double z = hitPoint.Z - cube.Content.Bounds.Z;
                cube.Transform = new TranslateTransform3D(x, 0, z);   //设置新的位置
                World.Children.Add(cube);
                unDoRedo.InsertInUnDoRedoForInsert(cube);
                isSave = false;//没有保存
            }
        }       
        /// <summary>
        /// 复制封装的方法
        /// </summary>
        private void NewCopy()
        {
            copyModel = new Cube();
            if (checkedModel != null)
            {
                hitPoint = new Point3D();
                //copyModel.Content = checkedModel.Content.Clone();
                // copyModel.Transform = checkedModel.Transform.Clone();//复制变换
                copyModel = checkedModel;
            }
            else
            {
                MessageBox.Show("请先选中物体");
            }
        }
        #endregion 
                 
        /// <summary>
        /// 给模型添加方向指针
        /// </summary>       
        private void GetDirection()
        {
            if (checkedModel != null && checkedModel.Content != null && (isScale || isTranslate))
            {
                //判断选中模型是否包含指针                
                if (!checkedModel.Children.Contains(direction))
                {
                    if (direction.Children.Count > 0)
                    {
                        checkedModel.Children.Add(direction);
                    }
                }
                ModelVisual3D directionBounds = direction.Children[0] as ModelVisual3D;
                //右侧中间
                double x = checkedModel.Content.Bounds.X + checkedModel.Content.Bounds.SizeX-directionBounds.Content.Bounds.X ;
                double y = checkedModel.Content.Bounds.Y + checkedModel.Content.Bounds.SizeY / 2 - directionBounds.Content.Bounds.Y;
                double z = checkedModel.Content.Bounds.Z + checkedModel.Content.Bounds.SizeZ / 2 - directionBounds.Content.Bounds.Z;               
                    direction.Transform = new TranslateTransform3D(x, y, z);                
            }
        }
        /// <summary>
        /// 读取工具箱目录文件
        /// </summary>
        void GetTools()
        {
            string path = Directory.GetCurrentDirectory() + "\\tools";
            if (!Directory.Exists(path))
            {
                MessageBox.Show("tools不存在");
                return;
            }

            //获得文件夹列表
            DirectoryInfo[] floders = new DirectoryInfo(path).GetDirectories();    
            foreach (DirectoryInfo diFloder in floders)
            {
                Grid grid = new Grid();
                TabItem tabItem = new TabItem();    
                tabTools.Items.Add(tabItem);
                tabItem.Header = diFloder.Name;
                tabItem.Style = (Style)this.FindResource("ToolTaItem");
                tabItem.Foreground = new SolidColorBrush(Colors.White);
                tabItem.Cursor = Cursors.Hand;
                //listbox
                ListBox listBox = new ListBox();
                Style style1 = (Style)this.FindResource("ToolListBox");
                listBox.Style = style1;
                listBox.BorderThickness = new Thickness(0);
                listBox.Margin = new Thickness(10, 0, 0, 0);
                listBox.Background = null;
                //添加到选项卡
                grid.Children.Add(listBox);
                tabItem.Content = grid;
                //item的样式
                Style itemStyle1 = (Style)this.FindResource("ToolListBoxItem");
                //添加取消
                ListBoxItem itemEscPublic1 = new ListBoxItem();
                StackPanel stackPanelEsc1 = new StackPanel();
                stackPanelEsc1.Orientation = Orientation.Horizontal;
                stackPanelEsc1.Margin = new Thickness(20, 5, 0, 0);
                Image imgEsc1 = new Image();
                imgEsc1.Width = 26;
                imgEsc1.Height = 25;
                Uri uriEsc1 = new Uri("Images/arrows.jpg", UriKind.Relative);
                BitmapImage bitmapEsc1 = new BitmapImage(uriEsc1);
                imgEsc1.Source = bitmapEsc1;
                TextBlock textBoxEsc1 = new TextBlock();
                textBoxEsc1.TextWrapping = TextWrapping.Wrap;
                textBoxEsc1.Text = "取消选择";
                textBoxEsc1.Foreground = new SolidColorBrush(Colors.White);
                textBoxEsc1.VerticalAlignment = VerticalAlignment.Center;
                textBoxEsc1.Margin = new Thickness(15, 0, 0, 0);
                stackPanelEsc1.Children.Add(imgEsc1);
                stackPanelEsc1.Children.Add(textBoxEsc1);
                itemEscPublic1.Content = stackPanelEsc1;
                itemEscPublic1.Tag = "";
                itemEscPublic1.Style = itemStyle1;
                itemEscPublic1.Selected += new RoutedEventHandler(item_Selected);
                listBox.Items.Add(itemEscPublic1);
                //    //获得子文件名称
                DirectoryInfo dir = new DirectoryInfo(diFloder.FullName);
                FileInfo[] chiFiles = dir.GetFiles("*.xml");
                foreach (FileInfo fl in chiFiles)
                {
                    //       //获得文件名，创建列表对象
                    ListBoxItem item = new ListBoxItem();
                    StackPanel stackPanel = new StackPanel();
                    stackPanel.Orientation = Orientation.Horizontal;
                    stackPanel.Margin = new Thickness(20, 5, 0, 0);
                    Image img = new Image();
                    img.Width = 26;
                    img.Height = 25;
                    string imgfile = fl.FullName.Substring(0, fl.FullName.IndexOf(fl.Extension)) + ".jpg";
                    Uri uri1 = new Uri("Resource/cn-zh/Images/Sofa.png", UriKind.Relative); ;
                    if (File.Exists(imgfile))
                    {
                        uri1 = new Uri(imgfile, UriKind.Absolute);
                    }
                    BitmapImage bitmap = new BitmapImage(uri1);
                    img.Source = bitmap;
                    TextBlock textBox = new TextBlock();
                    textBox.TextWrapping = TextWrapping.Wrap;
                    string fileName = fl.Name.Substring(0, fl.Name.LastIndexOf('.'));
                    item.ToolTip = fileName;//设置划过提示
                    if (fileName.Length > 6)
                    {
                        fileName = fileName.Substring(0, 6) + "...";
                    }
                    textBox.Text = fileName;
                    textBox.Foreground = new SolidColorBrush(Colors.White);
                    textBox.VerticalAlignment = VerticalAlignment.Center;
                    textBox.Margin = new Thickness(15, 0, 0, 0);
                    stackPanel.Children.Add(img);
                    stackPanel.Children.Add(textBox);
                    item.Content = stackPanel;

                    item.Tag = fl.FullName;
                    item.Style = itemStyle1;
                    item.Selected += new RoutedEventHandler(item_Selected);
                    listBox.Items.Add(item);
                }
            }

        }
        //工具箱选择模型
        void item_Selected(object sender, RoutedEventArgs e)
        {
            item = sender as ListBoxItem;
            modelFilePath = item.Tag.ToString();//模型路径
            //  modelType = item.Content.ToString();//模型类型
            if (modelFilePath.Equals(""))
            {
                isWrite = false;
            }
            else
            {
                isWrite = true;
            }
        }
    
        //隐藏工具栏
        private void btnHidden_Click(object sender, RoutedEventArgs e)
        {
            borTools.Width = 0;           
        }

        private void btnVisual_Click(object sender, RoutedEventArgs e)
        {
            borTools.Width = 250;          
        }
        //打开导入工具界面
        private void menuImportTools_Click(object sender, RoutedEventArgs e)
        {
            ImportTools dao = new ImportTools();
            dao.ShowDialog();
        }      

        /// <summary>
        /// 设置上一步模型坐标
        /// </summary>
        private void SetOldModel()
        {
            if (checkedModel != null)
            {
                //拉伸撤销对象
                oldModel.Content = checkedModel.Content.Clone();
                oldModel.Children.Clear();
                //添加而维对象，主要是文字
                foreach (Visual3D visual in checkedModel.Children)
                {
                    if (visual is Viewport2DVisual3D)
                    {
                        Viewport2DVisual3D visual2d = visual as Viewport2DVisual3D;
                        Viewport2DVisual3D visualNew = new Viewport2DVisual3D();
                        visualNew.Geometry = visual2d.Geometry.Clone();
                        oldModel.Children.Add(visualNew);
                    }
                }
            }
        }
        #region 属性更改事件
        #region //文本框值改变物体同步改变
        private void txtModelText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (checkedModel != null)
                {
                    //非传感器不让修改文本
                    if (checkedModel is Sensor)
                    {
                        checkedModel.Text = txtModelText.Text;
                    }
                }
            }
        }
        #endregion
        //修改模型名称
        private void txtModelName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (checkedModel != null && txtModelName.Text != "")
                {
                    //非传感器不让修改文本
                    if (checkedModel is Sensor)
                    {
                        checkedModel.Name = txtModelName.Text;
                    }
                }
            }
        }
        private void txtModelName_LostFocus(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtModelName.Text != "")
            {
                //非传感器不让修改文本
                if (checkedModel is Sensor)
                {
                    checkedModel.Name = txtModelName.Text;
                }
            }
        }
        private void txtModelText_LostFocus(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtModelText.Text != "")
            {
                //非传感器不让修改文本
                if (checkedModel is Sensor)
                {
                    checkedModel.Text = txtModelText.Text;
                }
            }
        }
        private void txtWidth_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (checkedModel != null && txtWidth.Text != "")
                {
                    CheckedEmpty(txtWidth);
                    SetOldModel();
                    double width = Convert.ToDouble(txtWidth.Text) / checkedModel.Content.Bounds.SizeZ - 1;
                    FlexByFrontToBack(width);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }

        private void txtLength_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (checkedModel != null && txtLength.Text != "")
                {
                    CheckedEmpty(txtLength);
                    SetOldModel();
                    double width = Convert.ToDouble(txtLength.Text) / checkedModel.Content.Bounds.SizeX - 1;
                    FlexByRound(width);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }

        private void txtHeight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (checkedModel != null && txtHeight.Text != "")
                {
                    CheckedEmpty(txtHeight);
                    SetOldModel();
                    double height = Convert.ToDouble(txtHeight.Text) / checkedModel.Content.Bounds.SizeY - 1;
                    FlexByUptoDown(height);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }
      
      //大小更改失去焦点
        private void txtWidth_LostFocus(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtWidth.Text != "")
            {
                CheckedEmpty(txtWidth);
                SetOldModel();
                double width = Convert.ToDouble(txtWidth.Text) / checkedModel.Content.Bounds.SizeZ - 1;
                if (width > 0)
                {
                    FlexByFrontToBack(width);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }

        private void txtLength_LostFocus(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtLength.Text != "")
            {
                CheckedEmpty(txtLength);
                SetOldModel();
                double width = Convert.ToDouble(txtLength.Text) / checkedModel.Content.Bounds.SizeX - 1;
                if (width > 0)
                {
                    FlexByRound(width);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }

        private void txtHeight_LostFocus(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtHeight.Text != "")
            {
                CheckedEmpty(txtHeight);
                SetOldModel();
                double height = Convert.ToDouble(txtHeight.Text) / checkedModel.Content.Bounds.SizeY - 1;
                if (height > 0)
                {
                    FlexByUptoDown(height);
                    unDoRedo.InsertInUnDoRedoForResize(oldModel, checkedModel);
                    isSave = false;//没有保存
                }
            }
        }
        /// <summary>
        /// 获得模型尺寸
        /// </summary>
        private void GetModelSize()
        {
            if (checkedModel.Content != null)
            {
                if (!checkedModel.Resize)
                {
                    spSize.IsEnabled = false;
                }
                else
                {
                    spSize.IsEnabled = true;
                }
                //tabTransform.Visibility = Visibility.Visible;
                txtWidth.Text = checkedModel.Content.Bounds.SizeZ.ToString();
                txtHeight.Text = checkedModel.Content.Bounds.SizeY.ToString();
                txtLength.Text = checkedModel.Content.Bounds.SizeX.ToString();
            }
        }
     

        //前
        private void btnTanslateFront_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateZ.Text!="")
            {
                double n = Convert.ToDouble(txtTranslateZ.Text);
                SetTranslateFrontToBack(n);
                TestCollision(0, n);
                unDoRedo.InsertInUnDoRedoForMove(0, 0, n, checkedModel);
                isSave = false;//没有保存
            }
        }
        //后
        private void btnTranslateBack_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateZ.Text != "")
            {
                double n = -Convert.ToDouble(txtTranslateZ.Text);
                SetTranslateFrontToBack(n);
                TestCollision(0, n);
                unDoRedo.InsertInUnDoRedoForMove(0, 0, n, checkedModel);
                isSave = false;//没有保存
            }
        }
        //左
        private void btnTranslateLeft_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateX.Text != "")
            {
                double n = -Convert.ToDouble(txtTranslateX.Text);
                SetTranslateRound(n);
                TestCollision(n, 0);
                unDoRedo.InsertInUnDoRedoForMove(n, 0, 0, checkedModel);
                isSave = false;//没有保存
            }
        }
        //右
        private void btnTranslateRight_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateX.Text != "")
            {
                double n = Convert.ToDouble(txtTranslateX.Text);
                SetTranslateRound(n);
                TestCollision(n, 0);
                unDoRedo.InsertInUnDoRedoForMove(n, 0, 0, checkedModel);
                isSave = false;//没有保存
            }
        }
        //上
        private void btnTranslateUp_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateY.Text != "")
            {
                double n = Convert.ToDouble(txtTranslateY.Text);
                SetTranslateUpToDown(n);
                TestCollision(n, 0);
                unDoRedo.InsertInUnDoRedoForMove(0, n, 0, checkedModel);
                isSave = false;//没有保存
            }
        }
        //下
        private void btnTranslateDown_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null && txtTranslateY.Text != "")
            {
                double n = -Convert.ToDouble(txtTranslateY.Text);
                SetTranslateUpToDown(n);
                //TestCollision(n, 0);
                unDoRedo.InsertInUnDoRedoForMove(0, n, 0, checkedModel);
                isSave = false;//没有保存
            }
        }
        #region   //按钮控制物体右转
        private void btnRoteRight_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null)
            {
                double n = 90;
                SetRotateRound(n);
                TestCollision(n, 0);
                unDoRedo.InsertInUnDoRedoForRotate(n, checkedModel);
            }
        }
        #endregion
        #region   //按钮控制物体左转
        private void btnRoteLeft_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null)
            {
                double n = -90;
                SetRotateRound(n);
                TestCollision(0, n);
                unDoRedo.InsertInUnDoRedoForRotate(n, checkedModel);
            }
        }
        #endregion
        #endregion

        #region 工具栏，菜单事件
 //新建
        private void menuNewFile_Click(object sender, RoutedEventArgs e)
        {
            NewFile newFile = new NewFile();
            if (newFile.ShowDialog().Value)
            {
                Drawing xin = new Drawing();
                xin.houseNum = newFile.houseNumber;
                xin.lblTitle.Content = newFile.houseNumber;
                xin.Show();
            }
            
        }  
        //打开，修改已保存的文件
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            menuOpen_Click(sender, e);            
        }      
        private void menuOpen_Click(object sender, RoutedEventArgs e)
        {
    //跳转到原始页面加载     
            //OpenFileDialog open = new OpenFileDialog();
            //open.Filter = "xaml|*.xml|所有文件|*.*";
            //if (open.ShowDialog().Value)
            //{
            //    Drawing xi = new Drawing(open.FileName);
            //    xi.Show();
            //}
            OpenFile openfile = new OpenFile();
            if (openfile.ShowDialog().Value)
            {
                //打开新窗口
              //  Drawing xin = new Drawing(fileStream);
               // xin.hmId = houseNumber;
               // xin.Show();
            }
        }

        private void OpenFile(String fileName)
        {
            
            //摄像机的变化用于新的场景
            Transform3D transform = World.Camera.Transform;
            try
            {
                using (FileStream file = new FileStream(fileName, FileMode.Open))
                {
                    Viewport3D view=XamlReader.Load(file) as Viewport3D;//场景新内容，覆盖以前内容，是一个新对象     
                    if (view != null)
                    {
                        grid.Children.Clear();//不能删除对象
                     //World.Children.Remove(line);//移出地板线
                        World = view;
                    }
                    else if(view==null)
                    {
                        throw new Exception("打开文件失败");
                    }
                    World.MouseDown += new System.Windows.Input.MouseButtonEventHandler(Word_MouseDown);
                    World.MouseMove += new MouseEventHandler(Word_MouseMove);
                    World.MouseUp += new MouseButtonEventHandler(Word_MouseUp);
                    World.Camera.Transform = transform;//设置摄像机变化
                    //还原视角
                    RestCamera();
                    grid.Children.Add(World);
                    //添加地板线
                    //World.Children.Add(line);
                    //添加方向方块                       
                    ProjectionCamera fCamera = fangXiang.Camera as ProjectionCamera;
                    grid.Children.Add(fangXiang);
                }
                //清空撤消队列
                unDoRedo.Cler();
                //添加撤消对象
                unDoRedo.Container = World;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void OpenFile(MemoryStream fileStream)
        {

            //摄像机的变化用于新的场景
            Transform3D transform = World.Camera.Transform;
            try
            {

                Viewport3D view = XamlReader.Load(fileStream) as Viewport3D;//场景新内容，覆盖以前内容，是一个新对象     
                    if (view != null)
                    {
                        grid.Children.Clear();//不能删除对象
                        //World.Children.Remove(line);//移出地板线
                        World = view;
                    }
                    else if (view == null)
                    {
                        throw new Exception("打开文件失败");
                    }
                    World.MouseDown += new System.Windows.Input.MouseButtonEventHandler(Word_MouseDown);
                    World.MouseMove += new MouseEventHandler(Word_MouseMove);
                    World.MouseUp += new MouseButtonEventHandler(Word_MouseUp);
                    World.Camera.Transform = transform;//设置摄像机变化
                    //还原视角
                    RestCamera();
                    grid.Children.Add(World);
                    //添加地板线
                    //World.Children.Add(line);
                    //添加方向方块                       
                    ProjectionCamera fCamera = fangXiang.Camera as ProjectionCamera;
                    grid.Children.Add(fangXiang);
                
                //清空撤消队列
                unDoRedo.Cler();
                //添加撤消对象
                unDoRedo.Container = World;
            }
            catch (Exception ex)
            {
               // SaveFile(fileStream, "downloadError_" + houseNum + ".xml");
                throw ex;
            }
        }
        //另存为
        private void menuSaveAs_Click(object sender, RoutedEventArgs e)
        {
            SaveAs();
        }
        //保存模板
        private void menuSaveTemplate_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog savedialog = new SaveFileDialog();
            savedialog.Filter = "xaml|*.xml|所有文件|*.*";
            if (savedialog.ShowDialog().Value)
            {
               Save(savedialog.FileName);//保存后就是这个文件路径
            }
            else
            {
                return;
            }
        }
       
        //导入3DMax文件
        private void menuImport_Click(object sender, RoutedEventArgs e)
        {
           WavefrontObjLoader wfl = new WavefrontObjLoader();
            try
            {
                OpenFileDialog opendialog = new OpenFileDialog();
                opendialog.Filter = "3DMax|*.obj";
                Cube modelOBJ = new Cube();
               if (opendialog.ShowDialog().Value)
                {
                    string fileName = opendialog.FileName;
                   int startIndex=fileName.LastIndexOf("\\")+1;
                   int endIndex=fileName.LastIndexOf('.')-startIndex;
                    modelOBJ = wfl.LoadObjFile(opendialog.FileName);
                    modelOBJ.Type = fileName.Substring(startIndex, endIndex);
                    // m.Transform = new TranslateTransform3D(0,0,0);
                }
                World.Children.Add(modelOBJ);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //退出
        private void menuExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        //工具栏移动按钮点击事件，设置当前为移动模式
        private void btnMove_Click(object sender, RoutedEventArgs e)
        {
            isTranslate = true;//设置模型移动状态
            isScale = false;
            isMoveWindow = false;
            GetDirection();
            ChangeButtonBackground(btnMove);
        }
        //工具栏拉伸按钮点击事件，设置当前为移动模式
        private void btnSize_Click(object sender, RoutedEventArgs e)
        {
            isScale = true;
            isTranslate = false;
            isMoveWindow = false;
           // if (checkedModel.Resize)//如果不是更改尺寸不添加指针
           // {
                GetDirection();
           // }
            ChangeButtonBackground(btnSize);
        }
        //俯视
        private void btnLookDownCamera_Click(object sender, RoutedEventArgs e)
        {
            LookDownCamera();
        }
        /// <summary>
        /// 俯视
        /// </summary>
        private void LookDownCamera()
        {
            //场景相机
            ProjectionCamera myCamera = World.Camera as ProjectionCamera;
            myCamera.Position = worldPoint3D;
            myCamera.LookDirection = lookDirection;
            myCamera.UpDirection = upDirection;
            if (myCamera.Transform != null)
            {
                Transform3DGroup group = myCamera.Transform as Transform3DGroup;
                foreach (Transform3D trans in group.Children)
                {
                    if (trans.GetType().Name.Equals("TranslateTransform3D"))
                    {
                        TranslateTransform3D tranLate = trans as TranslateTransform3D;
                        tranLate.OffsetX = 0;
                        tranLate.OffsetY = 0;
                        tranLate.OffsetZ = 0;
                    }
                    else if (trans.GetType().Name.Equals("RotateTransform3D"))
                    {
                        RotateTransform3D rotate = trans as RotateTransform3D;
                        AxisAngleRotation3D axis = rotate.Rotation as AxisAngleRotation3D;
                        axis.Angle = 0;
                        axis.Axis = new Vector3D(0, 1, 0);
                    }
                }
            }
            //方块还原
            ProjectionCamera fCamera = fangXiang.Camera as ProjectionCamera;
            fCamera.Position = fangXiangPoint3D;
            fCamera.LookDirection = lookDirection;
            fCamera.UpDirection = upDirection;
        }
        //挪地图
        private void btnDrag_Click(object sender, RoutedEventArgs e)
        {
            isTranslate = false;//设置模型移动状态
            isScale = false;
            isMoveWindow = true;
            ChangeButtonBackground(btnDrag);
        }
        //指针，清除变换状态
        private void btnArrows_Click(object sender, RoutedEventArgs e)
        {
            isTranslate = false;
            isScale = false;
            isMoveWindow = false;
            ChangeButtonBackground(btnArrows);
            if (checkedModel != null && checkedModel.Children.Count > 0)
            {
                if (checkedModel.Children.Contains(direction))
                {
                    checkedModel.Children.Remove(direction);
                }
            }
        }
        #region   //按钮控制保存物体
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {//判断是否是打开的文件
            //if (openFilePath == "")
            //{
               // System.Windows.Forms.FolderBrowserDialog savedialog = new System.Windows.Forms.FolderBrowserDialog();
                //savedialog.Filter = "xaml|*.xml|所有文件|*.*";
               // if (savedialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //{
                    //openFilePath = savedialog.SelectedPath;//保存后就是这个文件路径
               // if (!isSave)
                //{
                   // Save();
               // }
               // }
                //else
                //{
                   // return;
                //}
           // }
            if( !isSave)
            {
                Save();
            }
        }
       /// <summary>
        /// 保存户型图模板到本地
       /// </summary>
       /// <param name="filePath">保存的路径</param>
        private void Save(string filePath)
        {
                  
            try
            {
                //移出方向指针
                if (checkedModel != null && checkedModel.Children.Contains(direction))
                {
                    checkedModel.Children.Remove(direction);
                }
                //删除地板线
                World.Children.Remove(line);
                //删除地板
                World.Children.Remove(floor);

                //调整场景视角为俯视
                LookDownCamera();
                //创建一个内存流，这样就不保存文件了
                using (FileStream houseStream = new FileStream(filePath,FileMode.Create))
                {
                    //保存户型图图片
                    XamlWriter.Save(World, houseStream);
                }
                ModelVisual3D newFloor = DrawFloor.WriteFloor(World);
                //添加地板，地板大小随着户型大小变
                if (newFloor != null)
                {
                    floor = newFloor;
                }
                World.Children.Add(floor);
                string imgPath=filePath.Substring(0,filePath.LastIndexOf('.'))+".png";
                using (FileStream imgStream = new FileStream(imgPath, FileMode.Create))
                {
                    // render InkCanvas' visual tree to the RenderTargetBitmap
                    RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)World.ActualWidth, (int)World.ActualHeight, 96d, 96d, PixelFormats.Default);
                    targetBitmap.Render(World);
                    GenerateImage(targetBitmap, ImageFormat.PNG, imgStream);
                }

                // World.Children.Add(line);//添加线用于保存后当前界面显示
                isSave = true;//保存过了                
            }
            catch (Exception ex)
            {
                isSave = false;
                MessageBox.Show(ex.Message);
            }
            
            //}
        }
        /// <summary>
        /// 保存户型图到本地
        /// </summary>
        private void Save()
        {
            //创建一个内存流，这样就不保存文件了
            MemoryStream  houseStream = new MemoryStream();
            MemoryStream imgStream = new MemoryStream();
           
            string imgName = "";
            try
            {
                //判断编号，有编号就是修改和新建，没编号就生成编号
                if (houseNum == null || houseNum.Equals(""))
                {
                    NewFile newfile = new NewFile();
                    if (newfile.ShowDialog().Value)
                    {
                        houseNum = newfile.houseNumber;
                        lblTitle.Content = houseNum;
                    }
                    else
                    {
                        return;
                    }
                }
                    //文件尾号                  
                    m_houseName = houseNum + ".xml";
                    imgName = houseNum + ".png";
                
                //移出方向指针
                if (checkedModel != null && checkedModel.Children.Contains(direction))
                {
                    checkedModel.Children.Remove(direction);
                }
                //删除地板线
                World.Children.Remove(line);
                //删除地板
                World.Children.Remove(floor);

                //调整场景视角为俯视
                LookDownCamera();

                //保存户型图图片
                XamlWriter.Save(World, houseStream);            
                ModelVisual3D newFloor=DrawFloor.WriteFloor(World);
                //添加地板，地板大小随着户型大小变
                if (newFloor != null)
                {
                    floor = newFloor;                
                }              
                    World.Children.Add(floor);                

                // render InkCanvas' visual tree to the RenderTargetBitmap
                RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)World.ActualWidth, (int)World.ActualHeight, 96d, 96d, PixelFormats.Default);
                targetBitmap.Render(World);                
                GenerateImage(targetBitmap, ImageFormat.PNG, imgStream);

               
               // World.Children.Add(line);//添加线用于保存后当前界面显示

                /* 提交到服务器上*/
  
               //把流设置到起始位置
                houseStream.Seek(0, SeekOrigin.Begin);
                imgStream.Seek(0, SeekOrigin.Begin);
                //保存图片路径和名称
                imgInfo = new ArrayList();
               // imgInfo.Add(imgStream);
                imgInfo.Add(imgName);
                imgInfo.Add(m_floder + imgName);
                //保存到本地 
                SaveFile(imgStream, m_floder + imgName);
                m_filePath= m_floder+ m_houseName;
                SaveFile(houseStream, m_filePath);
               
               // Upload(houseName, m_filePath);
              //using (FileStream imgFileStream = new FileStream("house\\" + flode + "_"  + imgName, FileMode.Create))
              //{
              //    byte[] bt = new byte[imgStream.Length];
              //    imgStream.Read(bt, 0, bt.Length);
              //    imgFileStream.Write(bt, 0, bt.Length);
              //}
                isSave = true;//保存过了
                //TODO提交到服务器上
               // streamHelper.UploadFile(flode + "_" + imgName, "house\\" + flode + "_" + imgName, FileManager.Client.FileStreamService.FileManagerService.FileUsageType.Image);          

            }
            catch (Exception ex)
            {
                isSave = false;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (houseStream != null)
                {
                    houseStream.Close();
                }
                if (imgStream != null)
                {
                    imgStream.Close();
                }
            }
            //}
        }
       /// <summary>
       /// 保存到本地以便于上传
       /// </summary>
       /// <param name="houseStream">要保存的流</param>
       /// <param name="filePath">文件路径</param>
        public void SaveFile(Stream houseStream, string _filePath)
        {
            using (FileStream houseFileStream = new FileStream(_filePath, FileMode.Create))
            {
                byte[] bt = new byte[houseStream.Length];
                houseStream.Read(bt, 0, bt.Length);
                houseFileStream.Write(bt, 0, bt.Length);
                if (houseStream != null)
                {
                    houseStream.Dispose();
                }
            }
            if (houseStream != null)
            {
                houseStream.Dispose();
            }
        }
      /// <summary>
      /// 上传服务器
      /// </summary>
      /// <param name="houseName">户型图编号</param>
      /// <param name="flode">本地路径</param>
        private  void Upload( string _houseName, string _filePath)
        {
            //是否判断保存
            if (imgInfo==null||!isSave)
            {
                Save();
                _houseName = m_houseName;
                _filePath=m_filePath;
            }
            //图片没有上传
            if (File.Exists(_filePath))
            {
                streamHelper.UploadFile(_houseName, _filePath, FileManager.Client.FileStreamService.FileManagerService.FileUsageType.Image);
            }
            else
            {
                MessageBox.Show("要上传的文件不存在");
            }
        }
        /// <summary>
        /// 另存为
        /// </summary>
        private void SaveAs()
        {
            //SaveFileDialog savedialog = new SaveFileDialog();
            //savedialog.Filter = "xaml|*.xml|所有文件|*.*";
            //if (savedialog.ShowDialog().Value)
            //{
            //    Save(savedialog.FileName);//保存后就是这个文件路径
            //}
            //else
            //{
            //    return;
            //}
            if (!isSave)
            {
                Save();
            }
        }
        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="bitmap">图片源</param>
        /// <param name="format">图片格式</param>
        /// <param name="destStream">用于生成的流</param>
        void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream)
        {
            BitmapEncoder encoder = null;

            switch (format)
            {
                case ImageFormat.JPG:
                    encoder = new JpegBitmapEncoder();
                    break;
                case ImageFormat.PNG:
                    encoder = new PngBitmapEncoder();
                    break;
                case ImageFormat.BMP:
                    encoder = new BmpBitmapEncoder();
                    break;
                case ImageFormat.GIF:
                    encoder = new GifBitmapEncoder();
                    break;
                case ImageFormat.TIF:
                    encoder = new TiffBitmapEncoder();
                    break;
                default:
                    throw new InvalidOperationException();
            }

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(destStream);
        }
        /// <summary>
        /// 清楚保存在本地的文件
        /// </summary>
        private void ClearFile()
        {
            if (File.Exists("house\\" + houseNum + ".xml"))
            {
                File.Delete("house\\" + houseNum + ".xml");
            }
            if (File.Exists("house\\" + houseNum + ".png"))
            {
                File.Delete("house\\" + houseNum + ".png");
            }
        }
        //上传文件
        private void menuUpload_Click(object sender, RoutedEventArgs e)
        {
            Upload(m_houseName, m_filePath);
        }
        #endregion

       
        #region   //按钮控制删除物体
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            DelModel();
        }
        #endregion

        #region  按钮控制撤销
        private void btnUndo_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null)
            {
                checkedModel.Children.Remove(direction);
            }
            unDoRedo.Undo(1);
        }
        #endregion
        #region 按钮控制重做
        private void btnRedo_Click(object sender, RoutedEventArgs e)
        {
            if (checkedModel != null)
            {
                checkedModel.Children.Remove(direction);
            }
            unDoRedo.Redo(1);
        }
        #endregion
        #region //按钮控制复制
        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            NewCopy();
        }
        #endregion
        #region //按钮控制粘贴
        private void btnPatse_Click(object sender, RoutedEventArgs e)
        {
            Paste();
        }
        #endregion
        //还原视角
        private void btnRestCamera_Click(object sender, RoutedEventArgs e)
        {
            RestCamera();
        }
        /// <summary>
        /// 还原视角
        /// </summary>
        private void RestCamera()
        {
            //场景还原
            ProjectionCamera worlcamera = World.Camera as ProjectionCamera;
            worlcamera.Position = oldWorldCameraPoint;
            worlcamera.LookDirection = oldLookDirection;
            worlcamera.UpDirection = oldUpDirection;
            if (World.Camera.Transform != null)
            {
                Transform3DGroup group = World.Camera.Transform as Transform3DGroup;
                foreach (Transform3D trans in group.Children)
                {
                    if (trans.GetType().Name.Equals("TranslateTransform3D"))
                    {
                        TranslateTransform3D tranLate = trans as TranslateTransform3D;
                        tranLate.OffsetX = 0;
                        tranLate.OffsetY = 0;
                        tranLate.OffsetZ = 0;
                    }
                    else if (trans.GetType().Name.Equals("RotateTransform3D"))
                    {
                        RotateTransform3D rotate = trans as RotateTransform3D;
                        AxisAngleRotation3D axis = rotate.Rotation as AxisAngleRotation3D;
                        axis.Angle = 0;
                        axis.Axis = new Vector3D(0, 1, 0);
                    }
                }
            }
            //方块还原
            ProjectionCamera myCamera = fangXiang.Camera as ProjectionCamera;
            myCamera.Position = oldFangXiangCamera;
            myCamera.LookDirection = oldLookDirection;
            myCamera.UpDirection = oldUpDirection;
        }
        #endregion
      
       //关闭窗口
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!CloseWin())
            {
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <returns>true是关闭，false是不关闭</returns>
        private bool CloseWin()
        {
            bool isClose = true;
            if (!isSave)
            {
                MessageBoxResult result = MessageBox.Show("是否保存对文档的修改", "保存", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Yes)//保存
                {
                    //判断是否是打开的文件
                    //if (m_filePath == "")
                    //{
                    //    SaveFileDialog savedialog = new SaveFileDialog();
                    //    savedialog.Filter = "xaml|*.xml|所有文件|*.*";
                    //    if (savedialog.ShowDialog().Value)
                    //    {
                    //        m_filePath = savedialog.FileName;//保存后就是这个文件路径
                    //        Save();
                    //    }
                    //    else
                    //    {
                    //        isClose = false;
                    //    }
                    //}
                    //else
                    //{
                        Save();
                    //}
                }
                else if (result == MessageBoxResult.Cancel)//取消
                {
                    isClose = false;
                }
                else if (result == MessageBoxResult.No)//不保存
                {

                }
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("是否关闭当前文档", "关闭", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    isClose = false;
                }
                else
                {
                    isClose = true;
                }
            }
            return isClose;
        }
      
        //属性隐藏
        private void btnAttributeHidden_Click(object sender, RoutedEventArgs e)
        {
            splAttribute.Width = 0;
            splAttribute.Visibility = Visibility.Hidden;
        }
        //属性显示
        private void btnAttributeVisual_Click(object sender, RoutedEventArgs e)
        {
            splAttribute.Width = 200;
            splAttribute.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 改变按钮被点击之后的背景图片
        /// </summary>
        /// <param name="btn">要改变的按钮</param>
        public void ChangeButtonBackground(Button btn)
        {
           
            //设置前一个按钮的背景为没点击状态样式
            btn.Style = (Style)this.FindResource("SiderControlBtn");

            if (lastButton != null&&lastButton!=btn)
            {
                lastButton.Style = (Style)this.FindResource("ToolBtn");                
            }

            this.lastButton = btn;
        }
        /// <summary>
        /// 检测文本是否为空，为空就停止操作
        /// </summary>
        /// <param name="textBox">要检测的文本框</param>
        void CheckedEmpty(TextBox textBox)
        {
            if (textBox.Text.Equals(""))
            {
                return;
            }
        }

 #region 检查文本输入
        private void txtWidth_TextChanged(object sender, TextChangedEventArgs e)
        {
            //屏蔽中文输入和非法字符粘贴输入
            TextChangeCheck(sender, e);
        }

       
        private void txtLength_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChangeCheck(sender, e);
        }

        private void txtHeight_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChangeCheck(sender, e);
        }

        private void txtTranslateZ_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChangeCheck(sender, e);
        }

        private void txtTranslateX_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChangeCheck(sender, e);
        }

        private void txtTranslateY_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChangeCheck(sender, e);
        }

        /// <summary>
        /// 文本框输入和非法字符粘贴输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void TextChangeCheck(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                double num = 0;
                if (!Double.TryParse(textBox.Text, out num))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }
        }
        #endregion
        //最小化
        private void MinBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        //最大化
        private void MaxBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Boolean check = ((CheckBox)(e.Source)).IsChecked.Value;
            WindowStateToggle(check);
        }

        private void WindowStateToggle(Boolean check)
        {
            if (check)
            {
                this.Width = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
                this.Height = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
                this.Left = 0;
                this.Top = 0;
            }
            else
            {
                this.Width = 1000;
                this.Height = 720;
                this.Left = (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width - 1000) / 2.0;
                this.Top = (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - 720) / 2.0;
            }
        }
        //关闭
        private void CloseBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
          
                this.Close();
        
           // System.Windows.Application.Current.Shutdown();
        }
        private void TopBar_MouseMove(object sender, MouseButtonEventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
            if (e.ClickCount == 2)
            {
                bool check = chkToggle.IsChecked.Value;
               
                if (!check)
                {
                    chkToggle.IsChecked = true;
                    WindowStateToggle(true);
                }
                else
                {
                    chkToggle.IsChecked = false;
                    WindowStateToggle(false);
                }
                 
            }
        }

       
       

       

        //有个方法来添加选项卡、创建三维场景
    
       
    }
    /// <summary>
    /// 工具箱数据
    /// </summary>
    //class ToolBoxItem
    //{
    //    List<ToolItem> list = new List<ToolItem>();

    //    internal List<ToolItem> List
    //    {
    //        get { return list; }
    //        set { list = value; }
    //    }
    //    string name;

    //    public string Name
    //    {
    //        get { return name; }
    //        set { name = value; }
    //    }
    //}
    //class ToolItem
    //{
    //    Uri img;

    //    public Uri Img
    //    {
    //        get { return img; }
    //        set { img = value; }
    //    }
    //    string name;

    //    public string Name
    //    {
    //        get { return name; }
    //        set { name = value; }
    //    }
        
    //}
}
